package com.coocaa.ops.admin.v1.redis.service;

import com.coocaa.ops.common.core.base.model.R;
import com.coocaa.ops.common.core.biz.cache.constant.MatchConstants;
import com.coocaa.ops.common.core.biz.cache.enums.InterfaceCacheMethodEnums;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.cache.impl.MyCacheServiceImpl;
import com.coocaa.ops.common.tool.cache.util.ZipUtil;
import com.coocaa.ops.common.tool.exception.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

/**
 * @author bijiahao
 * @date : 2023/9/20 19:43
 * @description
 */
@Slf4j
@Service
public class CacheMgrService {
    @Autowired
    private MyCacheServiceImpl myCacheService;


    public R listKeyType() {
        InterfaceCacheMethodEnums[] methodEnums = InterfaceCacheMethodEnums.values();
        List<Map<String, String>> types = new ArrayList<>();
        for (InterfaceCacheMethodEnums methodEnum : methodEnums) {
            Map<String, String> type = InstanceUtil.newHashMap(24);

            type.put(methodEnum.name(), methodEnum.getDesc());

            types.add(type);
        }
        return R.ok(types);
    }

    /**
     * 获取缓存key列表，通过游标形式
     *
     * @param key
     * @param cacheEnv
     * @param scanCount
     * @param pageSize
     * @param matchPattern
     * @return
     */

    public R listKey(String key, String cacheEnv, Integer scanCount, Integer pageSize, Integer matchPattern) {
        String pattern = MatchConstants.getFinalKey(key, matchPattern);
        RedisTemplate<String, Serializable> redisTemplate = myCacheService.getRedisTemplate(cacheEnv);
        Set<String> keys = myCacheService.scanKeys(pattern, scanCount, pageSize, redisTemplate);
        if (key == null) {
            keys = Collections.emptySet();
        }
        return R.ok(keys.size(), keys);
    }


    public R getValByKey(String key, String cacheEnv) {
        Object value = this.get(key, cacheEnv);
        return R.ok().data(value);
    }


    public R delByKey(String[] keys, Integer matchPattern, String cacheEnv) {
        long count = 0;
        RedisTemplate<String, Serializable> redisTemplate = myCacheService.getRedisTemplate(cacheEnv);
        if (Objects.equals(matchPattern, 1)) {
            for (String key : keys) {
                long temp = myCacheService.deletePattern(key + "*", redisTemplate);
                count += temp;
            }
        } else {
            for (String key : keys) {
                boolean res = this.delete(key, cacheEnv);
                if (res) {
                    count++;
                }
            }
        }
        return R.ok().data("清理数量: " + count);
    }


    public R ttl(String key, String cacheEnv) {
        Long time = myCacheService.getRedisTemplate(cacheEnv).getExpire(key);
        return R.ok().data("存活时间/秒: " + time);
    }

    /*************** ===私有方法=== ********************* ===start=== ***************************************/

    private Object get(String key, String cacheEnv) {
        try {
            Serializable value = myCacheService.getRedisTemplate(cacheEnv).opsForValue().get(key);
            if (null == value) {
                return null;
            }
            String unZipVal = ZipUtil.gunzip(value.toString());
            return unZipVal;
        } catch (Exception e) {
            Map<String, Object> opParams = InstanceUtil.newHashMap(1);
            opParams.put("key", key);
            log.error(ExceptionUtil.getErrorPrintLog("从" + cacheEnv + "获取缓存", opParams, e));
            return null;
        }
    }

    private boolean delete(String key, String cacheEnv) {
        return myCacheService.getRedisTemplate(cacheEnv).delete(key);
    }
}
